import { getProductById } from '../api/detail'
import Vue from 'vue'
const product = {
  namespaced: true,
  state: {
    productList: []
  },
  mutations: {
    saveProductList (state, arr) {
      state.productList = [...arr]
    },
    addCart (state, { type, index }) {
      const prod = state.productList[type].content[index]
      if (prod.count) {
        Vue.set(prod, 'count', prod.count + 1)
      } else {
        Vue.set(prod, 'count', 1)
      }
    },
    reduceCart (state, { type, index }) {
      const prod = state.productList[type].content[index]
      if (prod.count) {
        Vue.set(prod, 'count', prod.count - 1)
      }
    },
    // 清空列表
    clearList (state) {
      state.productList.forEach(item => {
        item.content.forEach(prod => {
          if (prod.count) {
            prod.count = 0
          }
        })
      })
    }
  },
  getters: {
    selectList (state) {
      const result = []
      state.productList.forEach(item => {
        item.content.forEach(prod => {
          if (prod.count) {
            result.push(prod)
          }
        })
      })
      return result
    },
    // 计算总价
    totalPrice (state, getter) {
      return getter.selectList.reduce((price, prod) => {
        return price + prod.count * prod.price
      }, 0)
    },
    // 购物车总数量
    total (state, getter) {
      return getter.selectList.reduce((total, prod) => {
        return total + prod.count
      }, 0)
    }
  },
  actions: {
    // 请求商品列表
    getProductList ({ commit }, id) {
      return new Promise(resolve => {
        getProductById({
          id
        }).then(res => {
          const list = res.data.goods
          list.forEach((item, type) => {
            item.content.forEach((prod, index) => {
              prod.type = type
              prod.index = index
            })
          })
          commit('saveProductList', list)
          resolve()
        })
      })
    }
  }
}
export default product
